package com.controller.tiku;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.upload.UploadFile;
import com.model.*;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;


/**
 * Created by Hexun on 2017/5/30 0030.
 */
public class TikuImportController extends Controller{
    /**
    *@Author:HeXun
    *@Description:显示所有科目列表
    *@Date:2017/6/1 0001
    */
    public void showCourses(){
        List<Course> list=Course.dao.find("select * from courses where hasTiku=0");
        setAttr("CourseList",list);
        render("TikuImport.jsp");
    }
    //下载模版文件
    public void downloadTikuMuban(){
        renderFile("chutimuban.rar");
    }
    //上传题库文件，导入数据库
    public void importTiku(){
        UploadFile uplodaFile=getFile("file");
        final File file=uplodaFile.getFile();
        String filename=file.getName();
        final String courseId=getPara("courseId");
        //对上传文件需要进行验证
        if(filename.endsWith(".xls")){
            if(file.length()>0){
                Db.tx(new IAtom() {//事务处理
                    @Override
                    public boolean run() throws SQLException {
                        try{
                            importQuestion(file, courseId);
                            setAttr("Result", "导入题库成功");
                            return true;
                        } catch (Exception e) {
                            setAttr("Result", "导入模版错误，请按照模版进行更改");
                            e.printStackTrace();
                            return false;
                        }
                    }
                });
                }else{
                setAttr("Result","文件为空");
            }
        }else{
            setAttr("Result","请上传.xls文件");
        }
        //退出方法时将文件删除
        file.delete();
        //将科目列表带回页面
        List<Course> list=Course.dao.find("select * from courses");
        setAttr("CourseList",list);
        render("TikuImport.jsp");
    }
    /**
    *@Author:HeXun
    *@Description: 上传图片文件至WEB-INF/upload/pic下
    *@Date:2017/6/3 0003
    */
    public void importPic(){
        UploadFile uploadFile=getFile("picFile","pic");
        List<Course> list=Course.dao.find("select * from courses");
        setAttr("CourseList",list);
        if(uploadFile.getFile()!=null){
            setAttr("Result","导入图片成功");
        }else{
            setAttr("Result","导入失败");
        }
        render("TikuImport.jsp");
    }
    /**
    *@Author:HeXun
    *@Description: 设置不同类型题目的相同的部分：body,answer,chapter,rate,samelevel,course_id,frequency,imagename,point,createDate,score
    *@Date:2017/6/3 0003
    */
    public void setSame(Cell[] oneRow,Model m,String courseId){
        m.set("body",oneRow[1].getContents());
        m.set("answer",oneRow[2].getContents());
        if (oneRow[3] != null && !(oneRow[3].getContents().trim().equals(""))) {
            m.set("chapter",Integer.parseInt(oneRow[3].getContents().trim()));
        }else{
            m.set("chapter",0);
        }
        if (oneRow[4] != null && !(oneRow[4].getContents().trim().equals(""))) {
            m.set("rate",Integer.parseInt(oneRow[4].getContents().trim()));
        }else{
            m.set("rate",0);
        }
        if (oneRow[5] != null && !(oneRow[5].getContents().trim().equals(""))) {
            m.set("samelevel",oneRow[5].getContents());
        }else{
            m.set("samelevel",0);
        }
        Integer id = new Integer(courseId);
        m.set("course_id",id);
        m.set("frequency",2);
        if (oneRow[10] != null) {
            m.set("imagename",oneRow[10].getContents());
        }
        if (oneRow[11] != null && !(oneRow[11].getContents().trim().equals(""))) {
            m.set("point",oneRow[11].getContents());
        } else {
            m.set("point","");
        }
        Date createDate = new Date();
        m.set("createDate",createDate);
        m.set("score",oneRow[12].getContents());
    }
    /**
    *@Author:HeXun
    *@Description: 根据上传文件和科目导入文件中的题库
    *@Date:2017/6/3 0003
    */
    public void importQuestion(File file,String courseId)throws BiffException, IOException {
        Workbook book=Workbook.getWorkbook(file);
        Sheet sheet = book.getSheet(0);
        int rownum = sheet.getRows();
        Cell[] oneRow = new Cell[15];
        for (int i = 1; i < rownum; i++) {// i=0是第一行
            Cell[] oneRows = sheet.getRow(i);
            if (oneRows.length == 0 || "".equals(oneRows[0].getContents().trim())) {
                break;
            }
            int type = Integer.parseInt(oneRows[0].getContents().trim());
            System.out.println(type + "");
            if (type == 1) {
                Choice choice = new Choice();
                int l = oneRows.length;
                System.arraycopy(oneRows, 0, oneRow, 0, l);
                setSame(oneRow,choice,courseId);
                System.out.println(oneRow[6].getContents());
                choice.set("A",oneRow[6].getContents());
                choice.set("B",oneRow[7].getContents());
                choice.set("C",oneRow[8].getContents());
                choice.set("D",oneRow[9].getContents());
                choice.save();
            } else if (type == 2) {
                Judge judge = new Judge();
                int l = oneRows.length;
                System.arraycopy(oneRows, 0, oneRow, 0, l);
                setSame(oneRow,judge,courseId);
                judge.save();
            } else if(type == 3){
                SimpleFill sf = new SimpleFill();
                int l = oneRows.length;
                System.arraycopy(oneRows, 0, oneRow, 0, l);
                setSame(oneRow,sf,courseId);
                sf.save();
            }else if(type==4){
                ChoiceRead choiceread = new ChoiceRead();
                int l = oneRows.length;
                System.arraycopy(oneRows, 0, oneRow, 0, l);
                setSame(oneRow,choiceread,courseId);
                choiceread.set("sequence",Integer.parseInt(oneRow[13].getContents()));
                choiceread.save();
            }else if(type==5){
                SimplePress sp = new SimplePress();
                int l = oneRows.length;
                System.arraycopy(oneRows, 0, oneRow, 0, l);
                setSame(oneRow,sp,courseId);
                sp.save();
            }else if(type==6){
                Program sp = new Program();
                int l = oneRows.length;
                System.arraycopy(oneRows, 0, oneRow, 0, l);
                setSame(oneRow,sp,courseId);
                sp.save();
            }else if(type==7){
                ChoiceFill c = new ChoiceFill();
                int l = oneRows.length;
                System.arraycopy(oneRows, 0, oneRow, 0, l);
                setSame(oneRow,c,courseId);
                c.set("a",oneRow[6].getContents());
                c.set("b",oneRow[7].getContents());
                c.set("c",oneRow[8].getContents());
                c.set("d",oneRow[9].getContents());
                c.save();
            }else if(type==9){
                ComplexFill cf = new ComplexFill();
                int l = oneRows.length;
                System.arraycopy(oneRows, 0, oneRow, 0, l);
                setSame(oneRow,cf,courseId);
                cf.save();
            }
        }
        //设置科目已导入
        Course.dao.findById(courseId).set("hasTiku",1).update();
    }
}
